package com.ys.controller.api.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.base.TbUserJobLevelManage;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserJobLevelManageService;
import com.ys.service.base.TbUserMonthPerformanceService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 员工职级管理
 */
@Controller
@RequestMapping("/api/inter/tbUserJobLevelManage")
public class ApiInterTbUserJobLevelManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserJobLevelManageController.class);

    @Autowired
    private CommonApiService<TbUserJobLevelManage> commonApiService;

    @Autowired
    private TbUserJobLevelManageService tbUserJobLevelManageService;

    @Autowired
    private TbUserMonthPerformanceService tbUserMonthPerformanceService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserJobLevelManage setSeachSql(TbUserJobLevelManage cond){
        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS _ys_nameLinked")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.DeptName AS deptName");//部门

        cond.addLeftJoin("THR_UserArchives UA ON UA.UserId = A.UserId")//用户档案表
                .addField("UA.UserState AS userState")//员工状态
                .addField("UA.DingDingId AS dingDingId");//员工钉钉id

        cond.addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表
                .addField("O.OrgName AS orgName");//所属公司

        cond.addLeftJoin("TB_JobLevel J ON J.Id = A.RoleLevelId")//岗位职级表
                .addField("J.Rank AS rank")//岗位职级
                .addField("J.Category AS category")//岗位类别
                .addField("J.Categories AS categories")//职级大类
                .addField("J.Type AS roleLevelType")//岗位工种
                .addField("J.FixsalaryStandard AS fixsalaryStandard")//定薪标准/月
                .addField("J.SalaryStandard AS salaryStandard")//发薪标准/月
                .addField("J.FixedSalaryRatio AS fixedSalaryRatio")//固定薪资比例
                .addField("J.PerformanceRatio AS performanceRatio")//绩效薪资比例
                .addField("J.BasicSalary AS basicSalary")//基本底薪/月
                .addField("J.PositionSalary AS positionSalary")//岗位薪资/月
                .addField("J.PerbasedSalary AS perbasedSalary")//绩效薪资/月
                .addField("J.TransSubsidy AS transSubsidy")//交通补贴/月
                .addField("J.CateringSubsidy AS cateringSubsidy")//餐饮补贴/月
                .addField("J.JobPromotion AS jobPromotion")//岗位提奖/月
                .addField("J.QuarterlyBonus AS quarterlyBonus")//季度提奖/月
                .addField("J.AnnualBonus AS annualBonus");//年终奖标准（月）

        cond.addLeftJoin("TB_SocialSecurity S ON S.Id = A.SocialSecurityId")//社保管理表
                .addField("S.SoseBase AS soseBase")//社保基数
                //.addField("SUM(S.PiUnitMonth + S.UiUnitMonth + S.WiiUnitMonth) AS socialSecurityByCompany")//社保（单位）/月
                //.addField("SUM(S.PiRatioIndividual + S.UiIndividualMonth ) AS socialSecurityByPersonal")//社保（个人）/月
                .addField("S.PiUnitMonth AS piUnitMonth")
                .addField("S.UiUnitMonth AS uiUnitMonth")
                .addField("S.WiiUnitMonth AS wiiUnitMonth")
                .addField("S.PiRatioIndividual AS piRatioIndividual")
                .addField("S.UiIndividualMonth AS uiIndividualMonth")
                .addField("S.PiIndividualMonth AS piIndividualMonth")

        ;

        cond.addLeftJoin("TB_MedicalInsurance M ON M.Id = A.MedicalInsuranceId")//医保管理表
                .addField("M.MiBase AS miBase")//医保基数
                .addField("M.MiUnitMoonth AS miUnitMoonth")
                .addField("M.MiUnitMonth AS miUnitMonth")
                //.addField("SUM(M.MiUnitMoonth + M.MiUnitMonth) AS medicalInsuranceByCompany")//医保（单位）/月
                .addField("M.MiIndividualMonth AS medicalInsuranceByPersonal")//医保（个人）/月
        ;

        cond.addLeftJoin("TB_ProvidentFund P ON P.Id = A.AccumulationFundId")//公积金管理表
                .addField("P.HousingPfBase AS housingPfBase")//公积金基数
                .addField("P.PfUnitMonth AS providentFundByCompany")//公积金（单位）/月
                .addField("P.PfIndividualMonth AS providentFundByPersonal")//公积金（个人）/月
        ;

        cond.addLeftJoin("TB_Attendance AD ON AD.Id = A.AttendanceId")//考勤管理表
                .addField("AD.Type AS type");//考勤类型

        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MenuId.TB_UserJobLevelManage, cond);
        return cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate) throws Exception{
        List<Map<String, Object>> tableDate = new ArrayList();
        resDate.forEach(item->{
            BigDecimal socialSecurityByCompany = BigDecimal.ZERO;//社保（单位）/月
            BigDecimal socialSecurityByPersonal = BigDecimal.ZERO;//社保（个人）/月
            BigDecimal medicalInsuranceByCompany = BigDecimal.ZERO;//医保（单位）/月

            if(item.get("piUnitMonth")!=null){
                socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(item.get("piUnitMonth").toString()));
            }
            if(item.get("uiUnitMonth")!=null){
                socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(item.get("uiUnitMonth").toString()));
            }
            if(item.get("wiiUnitMonth")!=null){
                socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(item.get("wiiUnitMonth").toString()));
            }
            item.put("socialSecurityByCompany",socialSecurityByCompany);
            if(item.get("piIndividualMonth")!=null){
                socialSecurityByPersonal = socialSecurityByPersonal.add(new BigDecimal(item.get("piIndividualMonth").toString()));
            }
            if(item.get("uiIndividualMonth")!=null){
                socialSecurityByPersonal = socialSecurityByPersonal.add(new BigDecimal(item.get("uiIndividualMonth").toString()));
            }
            item.put("socialSecurityByPersonal",socialSecurityByPersonal);
            if(item.get("miUnitMoonth")!=null){
                medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(item.get("miUnitMoonth").toString()));
            }
            if(item.get("miUnitMonth")!=null){
                medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(item.get("miUnitMonth").toString()));
            }
            item.put("medicalInsuranceByCompany",medicalInsuranceByCompany);
            tableDate.add(item);
        });
        return tableDate;
    }



    /**
     * 查询
     */
    @RequiresPermissions("tbUserJobLevelManage:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TbUserJobLevelManage cond,String conditions){
		
		commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);

            //获取
            JSONArray tableVoJAData = tableVoJA.getData();
            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));

            //处理数据
            resList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);

            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserJobLevelManage cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserJobLevelManage)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            listData = setList(listData);

            //处理数据
            ExportExcelUtils<TbUserJobLevelManage> util = new ExportExcelUtils<>(new TbUserJobLevelManage());
            String toFilePath = util.exportExcel(listData, listField, "员工职级管理");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tbUserJobLevelManageService.save(params,MenuId.TB_UserJobLevelManage,true);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 推送至员工月度绩效信息
     */
    @RequestMapping("/pushToMonthPerformance")
    @ResponseBody
    public R pushToMonthPerformance(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String chooseMonth = params.get("chooseMonth").toString();
            //推送至员工月度绩效信息
            return tbUserMonthPerformanceService.addByJobLevelManage(idList,chooseMonth);
        } catch (Exception e) {
            logger.error("推送出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 编辑
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //编辑
            return tbUserJobLevelManageService.save(params,MenuId.TB_UserJobLevelManage,false);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



}